<template>
  <div>
    <div class="card flex flex-row gap-1">
      <el-select v-model="dictName" placeholder="请选择字典" style="width: 240px" @change="changeDictName">
        <el-option v-for="item in dictNameList" :key="item.value" :label="item.key" :value="item.value" />
      </el-select>
      <el-input v-model="queryText" placeholder="请输入查询条件" style="width: 240px" />
      <el-button type="primary" :disabled="(dictConfig?.items ?? []).length <= 0" @click="refresh"> 刷新 </el-button>
      <el-button type="primary" @click="save">保存</el-button>
      <el-button type="primary" @click="addItem">添加项目</el-button>
    </div>

    <div class="card" style="margin-top: 10px">
      <vxe-table
        ref="tableRef"
        :data="paginationRes?.data"
        :height="tableHeight"
        :edit-config="{
          trigger: 'click',
          mode: 'cell',
        }"
      >
        <vxe-column type="seq" title="序号" width="50" />
        <vxe-column
          v-for="item in dictConfig?.items || []"
          :key="item.columnName"
          :title="item.displayName"
          :field="item.columnName"
          :width="item.displayWidth"
          :edit-render="item.editable === '1' ? {} : undefined"
        >
          <template #edit="{ row }">
            <el-input v-model="row[item.columnName]" />
          </template>
        </vxe-column>
        <vxe-column title="操作" width="100" fixed="right">
          <template #default="{ row }">
            <el-button type="danger" size="small" @click="removeItem(row)">删除</el-button>
          </template>
        </vxe-column>
      </vxe-table>

      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="paginationRes?.total"
        :page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :current-page="currentPage"
        style="margin-top: 10px"
        size="small"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入表格组件
import { DictAPIs, type DictConfig, type EnumDictName } from '@/api/system/dict'
import { computed, ref, watch } from 'vue'
import { VxeTable, type VxeTableInstance } from 'vxe-table'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { PaginationRes } from '@/api/common'
import { EnumDictName2KeyValueArray } from '@/utils/dict'

const tableRef = ref<VxeTableInstance<any>>()

// 字典类型列表
const dictNameList = computed(() => {
  return EnumDictName2KeyValueArray()
})

const queryText = ref('')
const dictName = ref<EnumDictName>()
const dictConfig = ref<DictConfig | undefined>(undefined)
const paginationRes = ref<PaginationRes<any>>()
const currentPage = ref(1)
const pageSize = ref(10)

// 表高度
const tableHeight = computed(() => {
  return window.innerHeight - 200
})

// 选择字典
const changeDictName = async (val: EnumDictName) => {
  paginationRes.value = {
    data: [],
    total: 0,
  }

  dictConfig.value = await DictAPIs.getDictConfig(val)
  if (dictConfig.value.items.length <= 0) {
    ElMessage.warning('请先添加字典的显示项目')
    return
  }

  dictName.value = val
  await getData()
}

watch(
  () => [queryText.value, currentPage.value, pageSize.value],
  async () => {
    await getData()
  }
)

// 刷新数据
const refresh = async () => {
  currentPage.value = 1
  pageSize.value = 10

  await getData()
}

// 分页大小改变
const handleSizeChange = (val: number) => {
  pageSize.value = val
}

// 分页当前页改变
const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 获取数据
const getData = async () => {
  if (dictName.value === undefined) {
    ElMessage.warning('请选择字典')
    return
  }
  paginationRes.value = await DictAPIs.getDataByPagination({
    dictName: dictName.value,
    queryText: queryText.value,
    currentPage: currentPage.value,
    pageSize: pageSize.value,
    isPagination: false,
  })
}

//#region 数据维护
// 添加项目
const addItem = () => {
  const $table = tableRef.value
  if ($table) {
    if (dictName.value === undefined) {
      ElMessage.warning('请选择字典')
      return
    }
    $table.insert({})
  }
}

// 删除项目
const removeItem = (row: any) => {
  const $table = tableRef.value
  if ($table) {
    $table.remove(row)
  }
}

// 保存
const save = async () => {
  if (dictName.value === undefined) {
    ElMessage.warning('请选择字典')
    return
  }
  const $table = tableRef.value
  if ($table) {
    ElMessageBox.confirm('确定保存吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }).then(async () => {
      await DictAPIs.saveData({
        dictName: dictName.value as EnumDictName,
        data: {
          inserts: $table.getInsertRecords(),
          updates: $table.getUpdateRecords(),
          removes: $table.getRemoveRecords(),
        },
      })
      ElMessage.success('保存成功')
    })
  }
}
//#endregion
</script>
